<template>
  <div class="content_panel project_modules">
    <div class="content_panel_top">
      <h3 class="panel_title">
        <span>{{$t('finance.rolloverRecord')}}</span>
      </h3>
      <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
        <el-row>
          <el-col :span="4">
            <el-form-item prop="orderId" :class="{'required': isRecruiterLogin}">
              <el-input v-model="form.orderId" :placeholder="$t('common.innerOrderId')" clearable></el-input>
              <!--内部订单号-->
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="userPhone">
              <el-input v-model="form.userPhone" :placeholder="$t('common.mobileNumber')" clearable></el-input>
              <!--手机号码-->
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="userId" label="">
              <el-input v-model="form.userId" placeholder="User ID" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="lateDays" label="">
              <el-input v-model="form.lateDays" :placeholder="$t('common.extensionOverdueDays')" clearable></el-input>
              <!--展期时逾期天数-->
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="isRecruiterLogin">
            <el-form-item prop="collectionUserName" label="" :class="{'required': isRecruiterLogin}">
              <el-select v-model="form.collectionUserName" :placeholder="$t('common.recruiter')" clearable style="width: 100%">
                <!--催收、预催收员-->
                <el-option key="0" :value="userName" :label="userName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4" v-else>
            <el-form-item prop="collectionUserName" label="">
              <el-autocomplete style="width:100%" v-model="form.collectionUserName" :debounce="0" :fetch-suggestions="querySearch" :placeholder="$t('common.recruiter')" clearable></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item prop="appName" label="">
              <select-app-list v-model="form.appName" :placeholder="$t('system.appName')"></select-app-list>
              <!--app名称-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item prop="appPackage" label="">
              <el-input v-model="form.appPackage" :placeholder="$t('system.appPackage')" clearable></el-input>
              <!--app包名-->
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="extensionTime" style="width: 100%">
              <!--展期-->
              <el-date-picker v-model="form.extensionTime" type="datetimerange" format="yyyy-MM-dd HH:mm:ss" value-format="timestamp" :editable="false" style="width: 100%;" range-separator="-"
                :default-time="['00:00:00', '23:59:59']" :start-placeholder="$t('common.extensionStartTime')" :end-placeholder="$t('common.extensionEndTime')"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button @click="search" type="primary">{{ $t('common.search') }}</el-button>
            <el-button v-if="exportButtonShow" @click="exportData" type="primary">{{ $t('common.export') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="module_content">
      <div class="content_panel project_modules">
        <div class="table_list">
          <el-table ref="table" :data="tableData" style="width: 100%;" tooltip-effect="light" :max-height="tableMaxHeight" :highlight-current-row="true">
            <!--内部订单号-->
            <el-table-column prop="orderId" :label="$t('common.innerOrderId')" min-width="180"></el-table-column>
            <el-table-column prop="userId" label="User ID" min-width="100"></el-table-column>
            <!--姓名-->
            <el-table-column prop="userName" :label="$t('common.name')" min-width="150"></el-table-column>
            <!--手机号-->
            <el-table-column prop="userPhone" :label="$t('common.mobileNumber')" min-width="120"></el-table-column>
            <!--身份证号-->
            <el-table-column prop="userCardId" :label="$t('common.idCardNumber')" min-width="150"></el-table-column>
            <!--展期时间-->
            <el-table-column prop="extensionTime" :label="$t('common.extensionTime')" min-width="180">
              <template slot-scope="{ row }">{{ row.extensionTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
            </el-table-column>
            <!--展期天数-->
            <el-table-column prop="extensionDay" :label="$t('common.extensionDays')" min-width="120"></el-table-column>
            <!--新到期日-->
            <el-table-column prop="newRepayTime" :label="$t('common.newExpiryDate')" min-width="180">
              <template slot-scope="{ row }">{{ row.newRepayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
            </el-table-column>
            <!--原到期日-->
            <el-table-column prop="oldRepayTime" :label="$t('common.originalExpiryDate')" min-width="180">
              <template slot-scope="{ row }">{{ row.oldRepayTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
            </el-table-column>
            <!--展期时逾期天数-->
            <el-table-column prop="lateDays" :label="$t('common.extensionOverdueDays')" min-width="160"></el-table-column>
            <!--催收员-->
            <el-table-column prop="collectionUserName" :label="$t('common.recruiter')" min-width="150"></el-table-column>
            <!--APP名称-->
            <el-table-column prop="appName" :label="$t('system.appName')" min-width="130"></el-table-column>
            <!--APP包名-->
            <el-table-column prop="appPackage" :label="$t('system.appPackage')" min-width="130"></el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination @pageChange="pageChange" :page="page">
            <!--分页组件-->
          </pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Pagination from '@/components/pagination';
  import mixin from '@/service/mixin';
  import SelectAppList from '@/components/select-app-list';

  let that = null;
  export default {
    name: 'collection-extensionRecord',
    components: {
      Pagination,
      SelectAppList
    },
    mixins: [mixin],
    data() {
      return {
        tableData: [],
        form: {
          orderId: '',
          userPhone: '',
          userId: '',
          lateDays: '',
          collectionUserName: '',
          appName: '',
          appPackage: '',
          extensionTime: []
        },
        rules: {
          orderId: [
            { pattern: /^\d+$/, message: this.$t('verify.plsInputNumber') }
            // {validator: orderIdRule, trigger: ["blur",'change']}
          ],
          userPhone: [
            { pattern: /^\d+$/, message: this.$t('verify.plsInputNumber') }
          ]
        },
        isRecruiterLogin: false,
        userName: this.$storage.get('user').username,
        accountList: []
      };
    },
    computed: {
      exportButtonShow() {
        // 导出按钮展示权限
        return this.$store.getters.checkUserAuthority(
          'collection.extensionRecord.export'
        );
      }
    },
    methods: {
      // 获取列表数据
      async getTableData(page = this.page) {
        const params = this.fillParams(page);
        const {
          status,
          data,
          error
        } = await this.$api.collection.queryextensionrecord(params);
        if ('1' === status && '00000000' === error && data) {
          this.tableData = data.resultData;
          this.setPage(data.page, this.page);
        }
        this.tableMaxHeight = document.body.clientHeight - 265;
      },
      // 配置查询和导出参数
      fillParams(page = this.page) {
        const form = this.form;
        const params = {
          orderId: '',
          userPhone: '',
          userId: '',
          lateDays: '',
          collectionUserName: '',
          appName: '',
          appPackage: '',
          extensionTimelStart: '',
          extensionTimelEnd: '',
          page: {
            pageNo: page.currentPage,
            pageSize: this.page.pageSize
          }
        };
        Object.keys(form).forEach(key => {
          if (typeof form[key] === 'string' && form[key]) {
            form[key] = form[key].trim();
            params[key] = form[key];
          }
        });
        if (form.extensionTime && form.extensionTime.length >= 2) {
          params.extensionTimelStart = form.extensionTime[0];
          params.extensionTimelEnd = form.extensionTime[1];
        }
        return params;
      },
      search() {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (
              this.isRecruiterLogin &&
              !this.form.orderId &&
              !this.form.collectionUserName
            ) {
              this.$message.error(
                this.$t('verify.plsInputInnerOrderIdOrRecruiter')
              );
              return;
            }
            this.page.currentPage = 1;
            this.getTableData();
          }
        });
      },
      exportData() {
        this.$refs.form.validate(valid => {
          if (valid) {
            if (
              this.isRecruiterLogin &&
              !this.form.orderId &&
              !this.form.collectionUserName
            ) {
              this.$message.error(
                this.$t('verify.plsInputInnerOrderIdOrRecruiter')
              );
              return;
            }
            const params = this.fillParams();
            const user = this.$storage.get('user');
            const language = this.$storage.getLocal('language');
            params.language = language;
            params.token = user.token;
            const { $apiConf } = this;
            const url = this.$urlUtil.fillParams(
              params,
              $apiConf.baseUrl +
                $apiConf.urlType.collection.exprotextensionrecord,
              ['page']
            );
            this.$openNewBlank(url);
          }
        });
      },
      querySearch(queryString, cb) {
        let accountList = this.accountList;
        let results = queryString
          ? accountList.filter(this.createFilter(queryString))
          : accountList;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return account => {
          return (
            account.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          );
        };
      },
      async queryCollectorRole() {
        const {
          status,
          data,
          error
        } = await this.$api.collection.queryCollectorRole();
        if ('1' === status && '00000000' === error && data) {
          data.forEach(item => {
            if (item !== '128' && item !== '140' && item !== '129') {
              this.isRecruiterLogin = true;
            }
          });
          if (!this.isRecruiterLogin) {
            this.queryCollectorListAll();
          } else {
            this.form.collectionUserName = this.userName;
          }
          this.getTableData();
        }
      },
      // 根据当前登录角色获取所有催收员+预催员
      async queryCollectorListAll() {
        const {
          status,
          data,
          error
        } = await this.$api.collection.queryCollectorListAll();
        if ('1' === status && '00000000' === error && data) {
          this.accountList = data.map(item => {
            item.value = item.collectionUserName;
            return item;
          });
        }
      }
    },
    filters: {},
    created() {
      that = this;
      this.queryCollectorRole();
    }
  };
</script>
<style lang="scss" scoped>
  [data-page='collection-extensionRecord'] {
    .el-col {
      padding-left: 10px;
      position: relative;
    }
    .el-table .cell,
    .el-table th > .cell {
      word-break: keep-all;
      word-wrap: break-word;
    }
    .required::after {
      content: '*';
      color: #e65057;
      position: absolute;
      left: 2px;
      top: 4px;
    }
  }
</style>

